package com.hst.capacity.application.jpush.util;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hst.capacity.application.jpush.model.reponse.JPushDeviceInfo;
import com.hst.capacity.application.jpush.model.reponse.JPushResult;
import com.hst.capacity.application.jpush.model.request.JPushAudience;
import com.hst.capacity.application.jpush.model.request.JPushMessage;
import com.hst.capacity.application.jpush.model.request.JPushNotification;
import com.hst.capacity.application.jpush.model.request.JPushPlatform;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.Arrays;
import java.util.Base64;

public class JPushUtil {
//    private static final String appKey="a58986b6c0fcd656fb3524c8";
//    private static final String masterSecret="2d0a56914099e4837ff03f8d";

    private static final String appKey="61612ce29a5d49fe7e12dfa0";
    private static final String masterSecret="987c3c74532dc3da5471b521";


    /**
     * 发送自定义消息
     * @param registrationId 设备ID
     * @param content 自定义消息内容
     * @return
     */
    public static JPushResult sendMessage(String registrationId, String content, String title) {
        JPushPlatform jPushPlatform = new JPushPlatform();
        jPushPlatform.setPushAndroid(true);

        JPushAudience jPushAudience = new JPushAudience();
        jPushAudience.setRegistrationIds(new String[]{registrationId});


        JPushMessage jPushMessage = new JPushMessage();
        jPushMessage.setMsgContent(content);
        if (StringUtils.isNotBlank(title)){
            jPushMessage.setTitle(title);
        }

        return push(jPushPlatform, jPushAudience,null, jPushMessage);
    }

    //发送推送通知消息，最基础的4个参数方法 其他可选参考可采取方法重载的方式增加
    public static JPushResult push(JPushPlatform pushPlatform, JPushAudience pushAudience, JPushNotification pushNotification, JPushMessage pushMessage){
        if (pushPlatform.getParam() == null) {
            //设备类型不得为空
            throw new RuntimeException("Platform Error");
        }
        if (pushAudience.getParam() == null){
            //接收人不得为空
            throw new RuntimeException("Audience Error");
        }
        if(pushNotification == null && pushMessage==null){
            //消息或通知不得同时为空
            throw new RuntimeException("Body Error");
        }

        if(pushNotification!=null&&pushNotification.getParam()==null){
            //通知 Alert不得为空
            throw new RuntimeException("Notification Error");
        }
        if(pushMessage!=null&&pushMessage.getParam()==null){
            //自定义消息 msgContent不得为空
            throw new RuntimeException("PushMessage Error");
        }

        JSONObject params=new JSONObject();
        params.putAll(pushPlatform.getParam());
        params.putAll(pushAudience.getParam());

        if(pushNotification!=null){
            params.putAll(pushNotification.getParam());
        }
        if(pushMessage!=null){
            params.putAll(pushMessage.getParam());
        }

        String url="https://api.jpush.cn/v3/push";

        return executePostRequest(url, params);
    }

    /**
     * 根据设备ID查询标签、别名、手机号
     * @param registrationId 设备ID
     * @return JPushDeviceInfo 标签、别名、手机号
     */
    public static JPushDeviceInfo getDeviceInfoByRegistrationId(String registrationId){
        String url="https://device.jpush.cn/v3/devices/" + registrationId;
        JPushResult jPushResult = executeGetRequest(url);

        if(jPushResult!=null&&StringUtils.isNotBlank(jPushResult.getResult())){
            JSONObject jsonObject=JSONObject.parseObject(jPushResult.getResult());
            JPushDeviceInfo jPushDeviceInfo = new JPushDeviceInfo();
            String alias=jsonObject.getString("alias");
            String mobile=jsonObject.getString("mobile");
            JSONArray tags=jsonObject.getJSONArray("tags");

            jPushDeviceInfo.setMobile(mobile);
            jPushDeviceInfo.setAlias(alias);
            if(!tags.isEmpty()) {
                String[] tagsArray=new String[tags.size()];
                for (int i = 0; i < tags.size(); i++) {
                    if (tags.get(i) instanceof String){
                        tagsArray[i]=(String) tags.get(i);
                    }
                }
                jPushDeviceInfo.setTags(tagsArray);
            } else {
                jPushDeviceInfo.setTags(new String[]{});
            }
            return jPushDeviceInfo;
        }

        return null;
    }


    /**
     * 通过设备ID 设置标签、移除标签、别名、手机号
     * @param registrationId  设备ID
     * @param addTags 要增加的标签
     * @param removeTags 要移除的标签
     * @param alias 别名
     * @param mobile 手机号
     * @return
     */
    public static JPushResult saveDeviceInfo(String registrationId,String[] addTags,String[] removeTags,String alias,String mobile){

        String url="https://device.jpush.cn/v3/devices/" + registrationId;
        JSONObject params=new JSONObject();

        if((addTags!=null&&addTags.length>0)||(removeTags!=null&&removeTags.length>0)){
            JSONObject tags=new JSONObject();

            if(addTags!=null&&addTags.length>0){
                JSONArray jsonArray=new JSONArray();
                Arrays.stream(addTags).forEach(jsonArray::add);
                tags.put("add", jsonArray);
            }
            if(removeTags!=null&&removeTags.length>0){
                JSONArray jsonArray=new JSONArray();
                Arrays.stream(removeTags).forEach(jsonArray::add);
                tags.put("remove", jsonArray);
            }

            params.put("tags", tags);
        }

        if(StringUtils.isNotBlank(alias)){
            params.put("alias", alias);
        }
        if(StringUtils.isNotBlank(alias)){
            params.put("mobile", mobile);
        }

        return executePostRequest(url,params);
    }

    private static JPushResult executePostRequest(String url, JSONObject param){
        CloseableHttpClient client= HttpClients.createDefault();

        HttpUriRequest post= RequestBuilder.post(url)
                .setEntity(new StringEntity(param.toJSONString(), ContentType.APPLICATION_JSON))
                .setHeader("Authorization",getAuth())
                .build();

        try {
            HttpResponse response=client.execute(post);
            int status=response.getStatusLine().getStatusCode();
            String contentType=(response.getEntity()==null||response.getEntity().getContentType()==null)?"":response.getEntity().getContentType().toString();
            String result= response.getEntity()==null?"":EntityUtils.toString(response.getEntity());

            System.out.println("status==>" + status);
            System.out.println("contentType==>" + contentType);
            System.out.println("result==>" + result);

            JPushResult jPushResult = new JPushResult();
            jPushResult.setStatus(status);
            jPushResult.setContentType(contentType);
            jPushResult.setResult(result);

            return jPushResult;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static JPushResult executeGetRequest(String url) {
        CloseableHttpClient client= HttpClients.createDefault();

        HttpUriRequest get= RequestBuilder.get(url)
                .setHeader("Authorization",getAuth())
                .build();

        try {
            HttpResponse response=client.execute(get);
            int status=response.getStatusLine().getStatusCode();
            String contentType=(response.getEntity()==null||response.getEntity().getContentType()==null)?"":response.getEntity().getContentType().toString();
            String result= EntityUtils.toString(response.getEntity());

            System.out.println("status==>" + status);
            System.out.println("contentType==>" + contentType);
            System.out.println("result==>" + result);

            JPushResult jPushResult = new JPushResult();
            jPushResult.setStatus(status);
            jPushResult.setContentType(contentType);
            jPushResult.setResult(result);

            return jPushResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取Authorization
     * @return
     */
    private static String getAuth() {
        String str = appKey + ":" + masterSecret;
        try {
            byte[] decode = Base64.getEncoder().encode(str.getBytes());
            str= new String(decode, "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return "Basic "+str;
    }

}
